package com.ys.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class TxtUtil {
	/**
	 * 功能：Java读取txt文件的内容 步骤：
	 * 1：先获得文件句柄
	 * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 4：一行一行的输出。readline()。 备注：需要考虑的是异常情况
	 * 
	 * @param filePath
	 */
	public static String readTxtFile(String filePath) {
		StringBuffer sb = new StringBuffer("");
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return sb.toString();
	}
	/**
	 * 将内容写入TXT文件
	 * @param filePath 全路径，如：D:\\data\\upload\\txt\\
	 * @param fileName 文件名，如：dict.json
	 * @param content
	 */
	public static void writerTxtFile(String filePath, String fileName, String content) {
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		File reportFile = new File(filePath + "/"+ fileName);
		if (!reportFile.exists()){
			try {
				reportFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		OutputStream outputStream;
		try {
			outputStream = new FileOutputStream(reportFile);
			outputStream.write(content.getBytes(StandardCharsets.UTF_8));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String argv[]) {
//		String filePath = "D:\\temps\\test.txt";
//		System.out.println(readTxtFile(filePath));

		String filePath = "D:\\data\\upload\\txt\\";
		String fileName = "dict.json";
		writerTxtFile(filePath, fileName, "adfad ae vee");
	}
}